import { Http, Headers, Response,Jsonp, RequestOptions, URLSearchParams } from '@angular/http';
import 'rxjs/add/operator/toPromise';

import { Injectable } from '@angular/core';

import { Stop } from './stop';
import { SERVER } from '../../../app.config';

@Injectable()
export class StopService {
    constructor(private http: Http){
    }

    getStops(trip_id: number): Promise<Stop[]> {
        return this.http.get(SERVER.STOP + "?trip_id=" + trip_id)
        .toPromise()
        .then(response => response.json() as Stop[])
        .catch(this.handleError);
    }

    getStop(stop_id: number) {
        return this.http.get(SERVER.STOP + "/" + stop_id)
        .toPromise()
        .then(response => response.json() as Stop[])
        .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('错误：', error);

        return Promise.reject(error.message || error);
    }

    //添加
    private post(stop: Stop): Promise<Stop> {
        let headers = new Headers({
            'Content-type': 'application/json'});

        return this.http.post(SERVER.STOP, JSON.stringify(stop), {headers: headers})
        .toPromise()
        // .then(res => res.json().data)
        .catch(this.handleError);
    }

    //更新
    private put(stop: Stop): Promise<Stop> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.STOP}` + '/' + stop.stop_id;;
        console.log(stop.stop_name);

        return this.http.put(url, JSON.stringify(stop), {headers: headers})
                   .toPromise()
                   .then(() => stop)
                   .catch(this.handleError);
    }

    //删除
    delete(stop: Stop): Promise<Response> {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        let url = `${SERVER.STOP} +"/" + ${stop.stop_id}`;

        return this.http
                   .delete(url, { headers: headers})
                   .toPromise()
                   .catch(this.handleError);
    }

    //保存
    save(stop: Stop): Promise<Stop> {
        if (stop.stop_id) {
            return this.put(stop)
        }
        return this.post(stop);
    }
}